/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package util;

import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.activation.DataHandler;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.util.ByteArrayDataSource;

/**
 *
 * @author BlueZky
 */
public class MailUtils {
    private String userName = "";
    private String password = "";
    private String mailhost = "";
    private String mailer = "sendhtml";
    private String protocol = "";
    Properties prop = null;
    
    public MailUtils(){
        userName = "";
        password = "";
        prop = new Properties();
    }
    
    public  void getInstance(){
        try {
            InputStream is = getClass().getResourceAsStream("/mailProperties.properties");
            prop.load(is);
            userName = prop.getProperty("userName");
            password = prop.getProperty("password");
        } catch (IOException ex) {
            Logger.getLogger(MailUtils.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
    public void sendMail(String to, String cc, String bcc, String subject, String content){
        try {
            prop.put("mail.smtp.user", userName);
            prop.put("mail.smtp.password", password);
            
            Authenticator auth = new Authenticator() {
                @Override
                public PasswordAuthentication getPasswordAuthentication(){
                    return new PasswordAuthentication(userName, password);
                }
            };
            Session  session = Session.getDefaultInstance(prop, auth);
            Message msg = new MimeMessage(session);
            
            msg.setFrom(new InternetAddress(userName));
            msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to,false));
            msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc,false));
            msg.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(bcc, false));
            msg.setSubject(subject);
            msg.setDataHandler(new DataHandler(
		new ByteArrayDataSource(content, "text/html")));
            msg.setHeader("X-Mailer", mailer);
            msg.setHeader("Content-Type", "text/html; charset=UTF-8");
	    msg.setSentDate(new Date());
            
            Transport.send(msg);
            
        } catch (Exception ex) {
            Logger.getLogger(MailUtils.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}
